package com.taobao.me.api;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.taobao.base.model.RestResponse;
import com.taobao.base.model.TokenResponse;
import com.taobao.base.model.TokenUser;
import com.taobao.base.utils.SecurityUtil;
import com.taobao.me.feignclient.AuthServiceClient;
import com.taobao.me.model.dto.UserDto;
import com.taobao.me.model.po.Users;
import com.taobao.me.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@CrossOrigin
public class UserController {

    ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private UserService userService;

    @Autowired
    private AuthServiceClient authServiceClient;


//    @GetMapping("/test}")
//    public String test() {
//
//        TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
//        TradesSoldGetRequest req = new TradesSoldGetRequest();
//        req.setFields("tid,type,status,payment,orders,rx_audit_status");
//        req.setStartCreated(StringUtils.parseDateTime("2000-01-01 00:00:00"));
//        req.setEndCreated(StringUtils.parseDateTime("2000-01-01 23:59:59"));
//        req.setStatus("ALL_WAIT_PAY");
//        req.setBuyerNick("zhangsan");
//        req.setType("game_equipment");
//        req.setExtType("service");
//        req.setRateStatus("RATE_UNBUYER");
//        req.setTag("time_card");
//        req.setPageNo(1L);
//        req.setPageSize(40L);
//        req.setUseHasNext(true);
//        req.setBuyerOpenId("AAHm5d-EAAeGwJedwSHpg8bT");
//        TradesSoldGetResponse rsp = client.execute(req, sessionKey);
//        System.out.println(rsp.getBody());
//
//
//        return "test";
//    }



    /**
     * 插入用户
     */
    @PostMapping("/insertUser")
    public RestResponse<String> insertUser(@RequestBody Users users) {
        return userService.insertUser(users);
    }
    /**
     * 获取用户信息
     */
    @GetMapping("/getUserInfo")
    public RestResponse<UserDto> getUserInfo(HttpServletRequest request) {
        TokenUser tokenUser = getTokenUser(request);

        return userService.getUserById(tokenUser.getUserId());
    }

    @GetMapping("/getUserById/{userId}")
    public RestResponse<UserDto> getUserById(@PathVariable("userId") int userId) {

        System.out.println(userId);
        return userService.getUserById(userId);
    }

    @GetMapping("/getUserByToken")
    public RestResponse<UserDto> getUserByToken() {
       //取出当前用户身份
        SecurityUtil.TbUser user = SecurityUtil.getUser();
        System.out.println(user.getId());
        return userService.getUserById(user.getId());
    }

    /**
     * 根据id获取收货地址
     */
    @GetMapping("/getAddressById/{id}")
    public RestResponse<String> getAddressById(@PathVariable("id") int id) {

        System.out.println(id);

        // 假数据
        return RestResponse.success("削支签 北京朱雀街29号404");
    }



    /**
     * 解析token 获取用户信息
     */
    private TokenUser getTokenUser(HttpServletRequest request) {
        // 从请求头中获取 Authorization 字段
        TokenUser tokenUser = null;
        String authorizationHeader = request.getHeader("Authorization");
        // 检查是否包含 Bearer Token
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            String token = authorizationHeader.substring(7); // 去掉 "Bearer " 前缀
            TokenResponse tokenResponse = authServiceClient.checkToken(token);
            String jsonString = tokenResponse.getUser_name();
            // 转TokeUser对象
            try {
                tokenUser = objectMapper.readValue(jsonString, TokenUser.class);
                System.out.println(tokenUser);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        return tokenUser;
    }

}
